package com.cf.service.impl;

import com.cf.dao.ItemCategoryDao;
import com.cf.dao.ItemDao;
import com.cf.entity.Item;
import com.cf.entity.ItemCategory;
import com.cf.service.ItemCategoryService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 59899
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class ItemCategoryServiceImpl implements ItemCategoryService {
   @Autowired
    private ItemCategoryDao itemCategoryDao;
   @Autowired
   private ItemDao itemDao;

    @Override
    public List<ItemCategory> selectAllCategory() {
        List<ItemCategory> itemCategories = itemCategoryDao.selectAllCategory();
        for (ItemCategory itemCategory : itemCategories) {

            //通过cid查找项目
            List<Item> items = itemDao.selectItemByCid2(itemCategory.getCid());
            for (Item item: items){
                double  percentage =  item.getNmoney()/item.getAmoney()*100;
                long round = Math.round(percentage);
                item.setPercentage(round);
            }
            itemCategory.setItemList(items);

        }
        return itemCategories;
    }

    @Override
    public int addCategory(long iid, int[] cid) {
        Map map = new HashMap();
        map.put("iid",iid);
        for (int i = 0; i < cid.length; i++) {
            map.put("cid",cid[i]);
            int add = itemCategoryDao.addCategory(map);
            if (add == 0){
                return 0;
            }
        }
        return 1;
    }

    @Override
    public int deleteCategoryByIid(long iid) {
        return itemCategoryDao.deleteCategoryByIid(iid);
    }

    @Override
    public PageInfo<ItemCategory> selectAllLikeCname(int pageNum, String cname) {
        PageHelper.startPage(pageNum,5);
        List<ItemCategory> itemCategories = itemCategoryDao.selectAllLikeCname(cname);
        PageInfo<ItemCategory> categoryPageInfo = new PageInfo<>(itemCategories);
        return categoryPageInfo;
    }

    @Override
    public int deleteCategory(long cid) {
        return itemCategoryDao.deleteCategory(cid);
    }

    @Override
    public ItemCategory selectItemCategoryByCid(long cid) {
        return itemCategoryDao.selectItemCategoryByCid(cid);
    }

    @Override
    public int updateCategoryByCid(ItemCategory itemCategory) {
        return itemCategoryDao.updateCategoryByCid(itemCategory);
    }
}
